package com.daylightrobbery;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

public class UdpClient {

    public void run(int port) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel ch) {
                            ch.pipeline().addLast(new UdpClientHandler());
                        }
                    });

            Channel ch = b.bind(0).sync().channel(); // 自动绑定一个临时端口
            // 向服务器发送信息
            ByteBuf buf = Unpooled.copiedBuffer("Hello from UDP client", CharsetUtil.UTF_8);
            InetSocketAddress target = new InetSocketAddress("127.0.0.1", port);
            ch.writeAndFlush(new DatagramPacket(buf, target)).sync();

            // 客户端需要等待，以确保消息收发完成
            if (!ch.closeFuture().await(15000)) {
                System.out.println("Query timed out.");
            }
        } finally {
            group.shutdownGracefully();
        }
    }

    class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
        @Override
        public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) {
            String response = msg.content().toString(CharsetUtil.UTF_8);
            System.out.println("Received response: " + response);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            cause.printStackTrace();
            ctx.close();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int serverPort = 7777; // 服务端监听的端口
        new UdpClient().run(serverPort);
    }
}
